#include <nice2d/widgets/absolutelayout.h>

class AbsoluteLayoutInfo : public LayoutInfo
{
public:
    AbsoluteLayoutInfo(float ix,float iy):
        x(ix),
        y(iy)
    {
    }

    float x,y;
};

class AbsoluteLayoutData
{
public:
    std::map<ControlPointer,AbsoluteLayoutInfo> data;
};

IMPLEMENT_OBJECT(AbsoluteLayout,Layout)

AbsoluteLayout::AbsoluteLayout():
    data(new AbsoluteLayoutData())
{
    setLayoutResizeRule(LayoutResizeRule_ResizeLayout);
    setHResizeRule(ControlResizeRule_Fill);
    setVResizeRule(ControlResizeRule_Fill);
}

AbsoluteLayout::~AbsoluteLayout()
{
}

void AbsoluteLayout::addWidget(ControlPointer widget, float x, float y)
{
    auto info = std::make_shared<AbsoluteLayoutInfo>(x,y);
    Layout::addWidget(widget,info);
}

void AbsoluteLayout::adjust()
{
    auto count = getWidgetCount();
    if (count == 0)
        return;

    float margin = getMargin();

    float maxx = 0.0f;
    float maxy = 0.0f;

    for (uint32_t i = 0; i < count; i++) {
        auto item = getWidgetByIndex(i);
        auto widget = item.first;
        auto info = std::dynamic_pointer_cast<AbsoluteLayoutInfo>(item.second);
        if(info)
        {
            widget->setPosition(info->x + margin,info->y + margin);
            auto box = widget->getBoundingBox();
            maxx = std::max(maxx,box.left+box.width);
            maxy = std::max(maxy,box.top+box.height);
        }
    }

    if(getLayoutResizeRule() == LayoutResizeRule_ResizeLayout)
    {
        if(getHResizeRule() == ControlResizeRule_Fill)
            setWidth(maxx+getMargin());

        if(getVResizeRule() == ControlResizeRule_Fill)
            setHeight(maxy+getMargin());
    }
}
